package m.jclecai.com.fragment.goldManager;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.Response.ResponseSignList;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;


public class GoldExchangeFragment extends BaseFragment {


    @BindView(R.id.tv_my_gold_number)
    TextView mTvMyGoldNumber;
    @BindView(R.id.tv_exchange_money_max)
    TextView mTvExchangeMoneyMax;
    @BindView(R.id.et_exchange_money)
    EditText mEtExchangeMoney;
    @BindView(R.id.tv_need_gold_number)
    TextView mTvNeedGoldNumber;
    @BindView(R.id.tv_sure)
    TextView mTvSure;
    private UserBean mUserBean;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_gold_exchange;
    }

    @Override
    public void initData() {
        initUser();

        requestMyGoldNumber();
    }

    private void initUser() {
        mUserBean = PreferenceUtil.readUser(getActivity());
    }

    @Override
    public void initView() {
        mTvMyGoldNumber.setText("0");
    }

    @Override
    public void initListener() {

        mEtExchangeMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //这里我们需要判断一下；


                int totalGoldCoin=getTotalGoldCoin();

                int canExchangeMoney=totalGoldCoin/100;

                int inputMoney=formatInputNumberMoney(s.toString());

                if(inputMoney<=canExchangeMoney && inputMoney>=0){
                    //这里表示可以提交，刷新需要多少金币；
                    mTvNeedGoldNumber.setText("需要"+inputMoney*100+"金币");
                }else{
                    if(inputMoney > canExchangeMoney){
                        String canExchangeMoneyStr = canExchangeMoney + "";
                        mEtExchangeMoney.setText(canExchangeMoneyStr);
                        mEtExchangeMoney.setSelection(canExchangeMoneyStr.length());   //设置光标的位置；
                        mTvNeedGoldNumber.setText("需要"+canExchangeMoney*100+"金币");
                        DisPlayContent("您当前最多可兑换："+canExchangeMoney+"元");
                        return;
                    }

                    if(inputMoney <inputMoney){
                        mEtExchangeMoney.setText("0");
                        mEtExchangeMoney.setSelection(1);   //设置光标的位置；
                        mTvNeedGoldNumber.setText("需要0金币");
                        DisPlayContent("您当前最多可兑换："+canExchangeMoney+"元");
                        return;
                    }
                }
            }

            /**
             * 格式化输入的金额
             * @param numberMoney
             * @return
             */
            public int formatInputNumberMoney(String numberMoney){

                return formatStrToInt(numberMoney);
            }

            /**
             * 将字符串转换为Int类型；
             * @param str
             * @return
             */
            public int formatStrToInt(String str){
                int inputNumber = 0;
                try {
                    inputNumber= Integer.parseInt(str);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                return  inputNumber;
            }

            /**
             * 获取金币的金额；
             * @return
             */
            public int getTotalGoldCoin(){
                String myNumberMoney = mTvMyGoldNumber.getText().toString();
                return formatStrToInt(myNumberMoney);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //兑换彩金，请求网络进行一个兑换；
                String s = mEtExchangeMoney.getText().toString();
                if (s.length()<=0 || "0".equals(s)) {
                    DisPlayContent("请输入兑换的彩金");
                    return;
                }
                //这里我们要做的一个逻辑就是兑换彩金；
                exchagneMoney();
            }
        });
    }

    /**
     * 这里我们要做的一个操作就是请求网络去兑换彩金
     */
    private void exchagneMoney() {

        //这里我们是我们要兑换多少彩金；
        String numberStr = mEtExchangeMoney.getText().toString();
        final int numberMoney = Integer.parseInt(numberStr);

        //请求网络获取金币；
        if (mUserBean == null) {
            DisPlayContent("请先登录！！！");
            return;
        }
        String userName = PreferenceUtil.getUserName(getActivity());
        String password = PreferenceUtil.getPassword(getActivity());
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        pair.put("money",numberMoney+"");
        HttpManager.postAsyn(Constant_Url.EXCHANGE_MONEY, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！");
            }

            @Override
            public void onResponse(String response) {

                try {
                    ResponseSignList responseSignList = FastOk.get(response, ResponseSignList.class);
                    if(responseSignList!=null){

                        if ("0".equals(responseSignList.getStatus())) {
                            //这里我们要做的一个操作就是更新列表签到的列表；
                            //这里表示我们兑换成功；
                            DisPlayContent("兑换成功！！！");
                            //减少相应的金币的数量
                            int goldNumber = Integer.parseInt(mTvMyGoldNumber.getText().toString());
                            goldNumber=goldNumber-numberMoney*100;
                            mTvMyGoldNumber.setText(goldNumber+"");
                        }else{
                            DisPlayContent(responseSignList.getMessage());
                        }

                    }else{
                        DisPlay("网络异常！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常！");
                }

            }
        }, pair);


    }


    private void requestMyGoldNumber() {
        //请求网络获取金币；
        if (mUserBean == null) {
            DisPlayContent("请先登录！！！");
            return;
        }
        String userName = PreferenceUtil.getUserName(getActivity());
        String password = PreferenceUtil.getPassword(getActivity());
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        HttpManager.postAsyn(Constant_Url.SIGN_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlayContent("请检查网络！！！");
            }

            @Override
            public void onResponse(String response) {

                ResponseSignList responseSignList = FastOk.get(response, ResponseSignList.class);
                if ("0".equals(responseSignList.getStatus())) {
                    //这里我们要做的一个操作就是更新列表签到的列表；
                    String myGoldNumber=TextUtils.isEmpty(responseSignList.getGoldcoin())?"0":responseSignList.getGoldcoin();
                    mTvMyGoldNumber.setText(myGoldNumber);
                    int goldCoin = Integer.parseInt(TextUtils.isEmpty( responseSignList.getGoldcoin())?"0":responseSignList.getGoldcoin());
                    mTvExchangeMoneyMax.setText(goldCoin/100+"元");
                }else{
                    DisPlayContent(responseSignList.getMessage());
                }
            }
        }, pair);

    }

}
